package com.android.systemui.statusbar.board;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PathEffect;
import android.graphics.CornerPathEffect;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.Display;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Button;
import android.widget.TextView;
import android.widget.RadioGroup;
import android.util.DisplayMetrics;
import android.util.Log;
import android.app.Dialog;

import com.android.systemui.statusbar.board.BgPaintStyleAdapter;
import com.android.systemui.statusbar.board.ColorPicker;
import com.android.systemui.statusbar.board.HorizontalListView;

import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.widget.AdapterView;

import java.util.ArrayList;
import java.util.List;

import com.android.systemui.R;

public class ChoosePaintDialog implements View.OnClickListener, ColorPicker.OnColorChangedListener {

    private static final String TAG = "WindowUtils";

    private static final int[] icons = new int[]
            {
                    R.drawable.paint_indicator_0,
                    R.drawable.paint_indicator_1,
                    R.drawable.paint_indicator_2
            };

    private static final int[] bgPaintStyleResIds = new int[]
            {
                    R.drawable.bg_paint_style0,
                    R.drawable.bg_paint_style1,
                    R.drawable.bg_paint_style2,
                    R.drawable.bg_paint_style3,
                    R.drawable.bg_paint_style4,
                    R.drawable.bg_paint_style5,
                    R.drawable.bg_paint_style6,
                    R.drawable.bg_paint_style7
            };

    private ImageView ivWhite;
    private ImageView ivBlack;
    private ImageView ivEraser;

    private TextView tvPaint10;
    private TextView tvPaint20;
    private TextView tvPaint30;

    private View tvPaintSolid;
    private View tvPaintDashed;
    private View tvPaintBrush;

    private View pickerSelected;
    private ColorPicker picker;

    private HorizontalListView lvPaint;

    private ImageView viewPaint;

    private Paint paint;
    private Context mContext = null;

    private int levelIndex = 0; //画笔粗细级别包含橡皮擦
    private int currentColor;
    private boolean isEraser = false;

    public Boolean isShown = false;
    private Dialog mDialog;
    private DisplayMetrics mDisplayMetrics = new DisplayMetrics();
    private WindowManager wm;
    LayoutInflater layoutInflater;
    private Intent brushIntent;

    public ChoosePaintDialog(Context context, ImageView viewPaint) {
        this.mContext = context;
        this.viewPaint = viewPaint;
        wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        Display mDisplay = wm.getDefaultDisplay();
        mDisplay.getRealMetrics(mDisplayMetrics);
        layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    private void initDialog() {
        mDialog = new Dialog(mContext, R.style.FullHeightDialog);
        mDialog.getWindow().setGravity(Gravity.CENTER_HORIZONTAL);
        WindowManager.LayoutParams wmDParams = mDialog.getWindow().getAttributes();
        wmDParams.width = 100;
        wmDParams.height = 100;
        if (mDisplayMetrics.densityDpi > 240) {
            wmDParams.y = wm.getDefaultDisplay().getHeight() - 810;
        } else if (mDisplayMetrics.densityDpi > 160) {
            wmDParams.y = wm.getDefaultDisplay().getHeight() - 400;
        } else {
            wmDParams.y = wm.getDefaultDisplay().getHeight() - 200;
        }
        wmDParams.format = 1;
        mDialog.setContentView(getContentView());
        mDialog.getWindow().setAttributes(wmDParams);
        mDialog.getWindow().setType(2002);
        mDialog.setCanceledOnTouchOutside(true);
    }

    private View getContentView() {
        View view = layoutInflater.inflate(R.layout.pop_choose_paint, null);

        ivWhite = (ImageView) view.findViewById(R.id.iv_white);
        ivBlack = (ImageView) view.findViewById(R.id.iv_black);
        ivEraser = (ImageView) view.findViewById(R.id.iv_eraser);

        tvPaintSolid = view.findViewById(R.id.tv_paint_solid);
        tvPaintDashed = view.findViewById(R.id.tv_paint_dashed);
        tvPaintBrush = view.findViewById(R.id.tv_paint_brush);

        tvPaint10 = (TextView) view.findViewById(R.id.tv_paint_10);
        tvPaint20 = (TextView) view.findViewById(R.id.tv_paint_20);
        tvPaint30 = (TextView) view.findViewById(R.id.tv_paint_30);

        picker = (ColorPicker) view.findViewById(R.id.picker);
        pickerSelected = view.findViewById(R.id.iv_picker_selected);

        lvPaint = (HorizontalListView) view.findViewById(R.id.lv_paint);

        ivWhite.setOnClickListener(this);
        ivBlack.setOnClickListener(this);
        ivEraser.setOnClickListener(this);

        tvPaint10.setOnClickListener(this);
        tvPaint20.setOnClickListener(this);
        tvPaint30.setOnClickListener(this);

        tvPaintSolid.setOnClickListener(this);
        tvPaintDashed.setOnClickListener(this);
        tvPaintBrush.setOnClickListener(this);

        initColorView();
        drawColorView(ivWhite, getColor(R.color.white), true);
        drawStrokeView(0);
        initPathEffect();
        drawPathEffect(0, true);

        picker.setOnColorChangedListener(this);

        levelIndex = 0;

        currentColor = getColor(R.color.white);

        drawBottomPaintView();

        initPaintStyle();
        return view;
    }

    public void show() {
        if (mDialog == null) initDialog();
        mDialog.show();
    }

    public boolean isShowing() {
        return mDialog != null && mDialog.isShowing();

    }

    public void dismiss() {
        if (mDialog != null)
            mDialog.dismiss();
    }

    @Override
    public void onColorChanged(int color) {
        isEraser = false;
        currentColor = color;
        initColorView();
        pickerSelected.setVisibility(View.VISIBLE);
        drawBottomPaintView();
        setColor(currentColor, "white");
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_white:
                isEraser = false;
                currentColor = getColor(R.color.white);
                initColorView();
                drawColorView(ivWhite, getColor(R.color.white), true);
                drawBottomPaintView();
                setColor(getColor(R.color.white), "white");
                break;
            case R.id.iv_black:
                isEraser = false;
                currentColor = getColor(R.color.black);
                initColorView();
                drawColorView(ivBlack, getColor(R.color.black), true);
                drawBottomPaintView();
                setColor(getColor(R.color.black), "black");
                break;
            case R.id.iv_eraser:
                isEraser = true;
                initColorView();
                drawColorView(ivEraser, getColor(R.color.window_color), true);
                setPathEffect(new CornerPathEffect(0), "solid");
                initPathEffect();
                drawPathEffect(0, true);
                drawBottomPaintView();
                setColor(getColor(R.color.window_color), "eraser");
                break;
            case R.id.tv_paint_10:
                levelIndex = 0;
                drawStrokeView(0);
                setStrokeWidth(3);
                drawBottomPaintView();
                break;
            case R.id.tv_paint_20:
                levelIndex = 1;
                drawStrokeView(1);
                setStrokeWidth(7);
                drawBottomPaintView();
                break;
            case R.id.tv_paint_30:
                levelIndex = 2;
                drawStrokeView(2);
                setStrokeWidth(15);
                drawBottomPaintView();
                break;
            case R.id.tv_paint_solid:
                initPathEffect();
                drawPathEffect(0, true);
                setPathEffect(new CornerPathEffect(0), "solid");
                break;
            case R.id.tv_paint_dashed:
                initPathEffect();
                drawPathEffect(1, true);
                setPathEffect(new DashPathEffect(new float[]{20, 10}, 1), "dashed");
                break;
            case R.id.tv_paint_brush:
                initPathEffect();
                drawPathEffect(2, true);
                setPathEffect(new DashPathEffect(new float[]{20, 10}, 1), "brush");
                break;
        }
    }

    private void setColor(int color, String colorName) {
        if (paint != null) paint.setColor(color);
        brushIntent = new Intent("com.w2here.board.brush");
        brushIntent.putExtra("color", color);
        mContext.sendBroadcast(brushIntent);
    }

    private void setStrokeWidth(float width) {
        if (paint != null) paint.setStrokeWidth(width);
        brushIntent = new Intent("com.w2here.board.brush");
        brushIntent.putExtra("stroke", (int) width);
        mContext.sendBroadcast(brushIntent);
    }

    private void setPathEffect(PathEffect pathEffect, String type) {
        if (paint != null) paint.setPathEffect(pathEffect);
        brushIntent = new Intent("com.w2here.board.brush");
        brushIntent.putExtra("effect", type);
        mContext.sendBroadcast(brushIntent);
    }

    private void setBgStyle(int style) {
        brushIntent = new Intent("com.w2here.board.brush");
        brushIntent.putExtra("bgstyle", style);
        mContext.sendBroadcast(brushIntent);
    }

    private void initColorView() {
        pickerSelected.setVisibility(View.GONE);
        drawColorView(ivWhite, getColor(R.color.white), false);
        drawColorView(ivBlack, getColor(R.color.black), false);
        drawColorView(ivEraser, getColor(R.color.window_color), false);
    }

    //设置选中颜色指示器（圆环）
    private void drawColorView(ImageView imageView, int color, boolean isClicked) {
        int width = BoardUtil.dip2px(32);
        int height = BoardUtil.dip2px(32);
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(Color.TRANSPARENT);
        Paint paint = new Paint();
        paint.setColor(color == getColor(R.color.window_color) ? getColor(R.color.white) : color);
        paint.setAntiAlias(true);
        canvas.drawCircle(width / 2, height / 2, width / 2, paint);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(1);
        paint.setColor(getColor(R.color.gray));
        canvas.drawCircle(width / 2, height / 2, width / 2 - 1, paint);
        if (isClicked) {
            paint.setStrokeWidth(3);
            if (color != getColor(R.color.white) && color != getColor(R.color.window_color))
                paint.setColor(getColor(R.color.white));
            canvas.drawCircle(width / 2, height / 2, width / 2 - 4 - 3, paint);
        }
        imageView.setImageBitmap(bitmap);
    }

    private void drawStrokeView(int strokeWidth) {
        switch (strokeWidth) {
            case 0:
                tvPaint10.setBackgroundResource(R.drawable.gray_circle);
                tvPaint20.setBackgroundResource(R.drawable.grag_ring_1);
                tvPaint30.setBackgroundResource(R.drawable.grag_ring_2);
                break;
            case 1:
                tvPaint10.setBackgroundResource(R.drawable.grag_ring_0);
                tvPaint20.setBackgroundResource(R.drawable.gray_circle);
                tvPaint30.setBackgroundResource(R.drawable.grag_ring_2);
                break;
            case 2:
                tvPaint10.setBackgroundResource(R.drawable.grag_ring_0);
                tvPaint20.setBackgroundResource(R.drawable.grag_ring_1);
                tvPaint30.setBackgroundResource(R.drawable.gray_circle);
                break;
        }
    }

    private void initPathEffect() {
        drawPathEffect(0, false);
        drawPathEffect(1, false);
        drawPathEffect(2, false);
    }

    private void drawPathEffect(int index, boolean isClicked) {
        View changeView = null;
        if (index == 0) {
            changeView = tvPaintSolid;
        } else if (index == 1) {
            changeView = tvPaintDashed;
        } else if (index == 2) { //毛笔笔刷
            changeView = tvPaintBrush;
        }
        if (changeView != null)
            changeView.setBackgroundResource(isClicked ?
                    R.drawable.gray_circle : R.drawable.gray_ring_transparent);
    }

    private void drawBottomPaintView() {
        Resources r = mContext.getResources();
        if (isEraser) {
            viewPaint.setImageDrawable(r.getDrawable(R.drawable.level_no_eraser));
            return;
        }
        Drawable[] layers = new Drawable[2];
        layers[0] = new ColorDrawable(currentColor);
        layers[1] = r.getDrawable(icons[levelIndex]);
        LayerDrawable layerDrawable = new LayerDrawable(layers);
        viewPaint.setImageDrawable(layerDrawable);
    }

    private void initPaintStyle() {
        final List<BgPaintStyleAdapter.BgPaintStyle> bgPaintStyles = new ArrayList<>();
        for (int bgPaintStyleResId : bgPaintStyleResIds) {
            BgPaintStyleAdapter.BgPaintStyle style = new BgPaintStyleAdapter.BgPaintStyle();
            style.resId = bgPaintStyleResId;
            bgPaintStyles.add(style);
        }
        bgPaintStyles.get(0).isSelected = true;
        final BgPaintStyleAdapter adapter = new BgPaintStyleAdapter(bgPaintStyles);
        adapter.setSelectedPos(0); //默认第一个选中
        lvPaint.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                bgPaintStyles.get(adapter.getSelectedPos()).isSelected = false;
                bgPaintStyles.get(position).isSelected = true;
                adapter.setSelectedPos(position);
                adapter.notifyDataSetChanged();
                setBgStyle(position);
            }
        });
        lvPaint.setAdapter(adapter);
    }

    private int getColor(int id) {
        return mContext.getResources().getColor(id);
    }

}
